import { VirtualList, VirtualListProps } from '@nutui/nutui-react-taro';
import { useRequest, FunctionType } from './useRequest';
import { useEffect, useMemo, useState } from 'react';

interface UseListProps<P, R>
  extends Omit<VirtualListProps, 'list' | 'onScroll'> {
  fn: FunctionType<P, R>;
  pageNo?: number;
  pageSize?: number;
  options?: Record<string, any>;
}

export function useList<P, R>({
  pageNo = 1,
  pageSize = 10,
  fn,
  options,
  ...rest
}: UseListProps<P, R>) {
  const [innerPageNo, setInnerPageNo] = useState<number>(pageNo);

  const params = useMemo(
    () =>
      ({
        pageNo: innerPageNo,
        pageSize,
        manual: true,
        ...options,
      }) as P,
    [options, innerPageNo, pageSize],
  );

  const { data, run, loading } = useRequest(fn, { ...params } as any);

  useEffect(() => {
    run(params);
  }, [params]);

  const onScroll = () => {
    if (loading) return;
    setInnerPageNo((prev) => prev + 1);
  };

  return <VirtualList {...rest} list={data} onScroll={onScroll} />;
}
